import React, { useState, useEffect, useRef } from 'react';
import {
  View,
  Text,
  StyleSheet,
  Dimensions,
  TouchableOpacity,
  Alert,
  useTVEventHandler,
} from 'react-native';
import { Card } from '../types/Card';
import SecureImageView from './SecureImageView';
import AudioService from '../services/AudioService';
import DatabaseService from '../services/DatabaseService';

interface CardViewProps {
  card: Card;
  onFlip?: () => void;
  onNext?: () => void;
  onPrevious?: () => void;
  onBack?: () => void;
  onRead?: () => void;
  onDownload?: () => void;
  onDelete?: () => void;
  onToggleDisplay?: () => void; // 添加显示模式切换回调
  serverInfo?: any;
  isLocal?: boolean;
  isDownloading?: boolean;
  isPlaying?: boolean;
  isLoadingAudio?: boolean;
  localCard?: Card | null;
  showUpdateButton?: boolean;
  showCardImages?: boolean; // 添加显示模式参数
}

const { width, height } = Dimensions.get('window');

const CardView: React.FC<CardViewProps> = ({
  card,
  onFlip,
  onNext,
  onPrevious,
  onBack,
  onRead,
  onDownload,
  onDelete,
  onToggleDisplay,
  serverInfo,
  isLocal = false,
  isDownloading = false,
  isPlaying = false,
  isLoadingAudio = false,
  localCard = null,
  showUpdateButton = false,
  showCardImages = true, // 默认显示图片
}) => {
  const [isFlipped, setIsFlipped] = useState(!showCardImages); // 根据显示模式设置初始翻转状态
  const [isLoading, setIsLoading] = useState(false);

  const flipButtonRef = useRef<any>(null);
  const previousButtonRef = useRef<any>(null);
  const nextButtonRef = useRef<any>(null);
  const backButtonRef = useRef<any>(null);

  // TV 按键处理
  useTVEventHandler((evt: any) => {
    const { eventType } = evt;
    
    switch (eventType) {
      case 'left':
        handlePrevious();
        break;
      case 'right':
        handleNext();
        break;
      case 'up':
        handleRead();
        break;
      case 'down':
        if (!isLocal) {
          handleDownload();
        }
        break;
      case 'select':
      case 'enter':
        handleToggleDisplay(); // 改为调用显示模式切换
        break;
      case 'menu': // 添加菜单键处理，用于删除功能
        if (isLocal) {
          handleDelete();
        }
        break;
      case 'back':
        if (onBack) {
          onBack();
        }
        break;
    }
  });

  const handleFlip = () => {
    setIsFlipped(!isFlipped);
    if (onFlip) {
      onFlip();
    }
  };

  const handleToggleDisplay = () => {
    if (onToggleDisplay) {
      onToggleDisplay();
    }
  };

  const handleNext = () => {
    if (onNext) {
      onNext();
    }
  };

  const handlePrevious = () => {
    if (onPrevious) {
      onPrevious();
    }
  };

  const handleRead = () => {
    if (onRead) {
      onRead();
    }
  };

  const handleDownload = () => {
    if (onDownload) {
      onDownload();
    }
  };

  const handleDelete = () => {
    if (onDelete) {
      onDelete();
    }
  };

  // 获取下载按钮文本
  const getDownloadButtonText = () => {
    if (isLocal) {
      return '删除'; // 删除按钮改为菜单键图标
    }
    
    if (isDownloading) {
      return '下载中...';
    }
    
    if (localCard !== null) {
      if (showUpdateButton) {
        return '🔄 更新';
      } else {
        return '✅ 已下载';
      }
    }
    
    return '📥 下载';
  };

  // 获取下载按钮是否禁用
  const isDownloadButtonDisabled = () => {
    if (isLocal) {
      return false; // 删除按钮不禁用
    }
    return isDownloading || (!isLocal && localCard !== null && !showUpdateButton);
  };

  // 获取下载按钮样式
  const getDownloadButtonStyle = () => {
    if (isLocal) {
      return [styles.cornerButton, styles.downloadButton, styles.deleteButton];
    }
    
    if (isDownloading) {
      return [styles.cornerButton, styles.downloadButton, styles.downloadingButton];
    }
    
    if (localCard !== null) {
      if (showUpdateButton) {
        return [styles.cornerButton, styles.downloadButton, styles.updateButton];
      } else {
        return [styles.cornerButton, styles.downloadButton, styles.downloadedButton];
      }
    }
    
    return [styles.cornerButton, styles.downloadButton];
  };

  // 获取下载按钮点击处理函数
  const getDownloadButtonHandler = () => {
    if (isLocal) {
      return handleDelete;
    }
    return handleDownload;
  };

  return (
    <View style={styles.container}>
      {/* 左侧导航按钮 */}
      <TouchableOpacity
        ref={previousButtonRef}
        style={[styles.navButton, styles.leftNavButton]}
        onPress={handlePrevious}
        tvParallaxProperties={{ enabled: true }}
      >
        <Text style={styles.navButtonText}>◀ 上一张</Text>
      </TouchableOpacity>

      {/* 中央卡片内容 */}
      <View style={styles.cardContainer}>
        <TouchableOpacity
          style={[styles.card, isFlipped && styles.cardFlipped]}
          onPress={handleFlip}
          activeOpacity={0.9}
        >
          {!isFlipped ? (
            // 正面 - 显示图片
            <View style={styles.frontSide}>
              <SecureImageView
                source={{ uri: card.front_image }}
                style={styles.cardImage}
                serverInfo={serverInfo}
                onLoadStart={() => setIsLoading(true)}
                onLoadEnd={() => setIsLoading(false)}
              />
              {isLoading && (
                <View style={styles.loadingContainer}>
                  <Text style={styles.loadingText}>加载中...</Text>
                </View>
              )}
            </View>
          ) : (
            // 背面 - 显示文字
            <View style={styles.backSide}>
              <Text style={styles.backText}>{card.back_text}</Text>
            </View>
          )}
        </TouchableOpacity>
      </View>

      {/* 右侧导航按钮 */}
      <TouchableOpacity
        ref={nextButtonRef}
        style={[styles.navButton, styles.rightNavButton]}
        onPress={handleNext}
        tvParallaxProperties={{ enabled: true }}
      >
        <Text style={styles.navButtonText}>下一张 ▶</Text>
      </TouchableOpacity>

      {/* 左下角下载/删除按钮 */}
      <TouchableOpacity
        style={getDownloadButtonStyle()}
        onPress={getDownloadButtonHandler()}
        tvParallaxProperties={{ enabled: true }}
        disabled={isDownloadButtonDisabled()}
      >
        <Text style={styles.cornerButtonText}>{getDownloadButtonText()}</Text>
      </TouchableOpacity>

      {/* 右下角朗读按钮 */}
      <TouchableOpacity
        style={[styles.cornerButton, styles.audioButton]}
        onPress={handleRead}
        tvParallaxProperties={{ enabled: true }}
        disabled={isLoadingAudio}
      >
        {isLoadingAudio ? (
          <Text style={styles.cornerButtonText}>加载中...</Text>
        ) : (
          <Text style={styles.cornerButtonText}>
            {isPlaying ? '⏹️ 停止' : (card.audio_path ? '🔊 朗读' : '🔇 无音频')}
          </Text>
        )}
      </TouchableOpacity>

      {/* 返回按钮 */}
      <TouchableOpacity
        ref={backButtonRef}
        style={styles.backButton}
        onPress={onBack}
        tvParallaxProperties={{ enabled: true }}
      >
        <Text style={styles.backButtonText}>返回</Text>
      </TouchableOpacity>

      {/* 遥控器按键提示 */}
      <View style={styles.remoteHintContainer}>
        <Text style={styles.remoteHintText}>◀▶ 左右键: 切换卡片</Text>
        <Text style={styles.remoteHintText}>↑ 上键: 朗读</Text>
        <Text style={styles.remoteHintText}>↓ 下键: 下载</Text>
        <Text style={styles.remoteHintText}>OK键: 翻转</Text>
        {isLocal && <Text style={styles.remoteHintText}>MENU键: 删除</Text>}
        <Text style={styles.remoteHintText}>BACK键: 返回</Text>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a1a1a',
    position: 'relative',
  },
  cardContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 100,
  },
  card: {
    height: '100%',
    aspectRatio: 1,
    backgroundColor: '#ffffff',
    borderRadius: 20,
    padding: 20,
    justifyContent: 'center',
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 10,
    },
    shadowOpacity: 0.3,
    shadowRadius: 20,
    elevation: 10,
  },
  cardFlipped: {
    backgroundColor: '#f0f0f0',
  },
  frontSide: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    width: '100%',
  },
  backSide: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    width: '100%',
    padding: 20,
  },
  cardImage: {
    width: '100%',
    height: '100%',
    borderRadius: 10,
  },
  backText: {
    fontSize: 28,
    color: '#333',
    textAlign: 'center',
    lineHeight: 40,
    fontWeight: '500',
  },
  loadingContainer: {
    position: 'absolute',
    justifyContent: 'center',
    alignItems: 'center',
  },
  loadingText: {
    fontSize: 18,
    color: '#666',
  },
  hintText: {
    color: '#888',
    fontSize: 14,
    textAlign: 'center',
  },
  navButton: {
    position: 'absolute',
    top: '50%',
    transform: [{ translateY: -25 }],
    backgroundColor: '#4a90e2',
    paddingHorizontal: 20,
    paddingVertical: 15,
    borderRadius: 25,
    borderWidth: 2,
    borderColor: 'transparent',
    zIndex: 10,
  },
  leftNavButton: {
    left: 20,
  },
  rightNavButton: {
    right: 20,
  },
  navButtonText: {
    color: '#ffffff',
    fontSize: 16,
    fontWeight: 'bold',
  },
  cornerButton: {
    position: 'absolute',
    paddingHorizontal: 20,
    paddingVertical: 12,
    borderRadius: 20,
    borderWidth: 2,
    borderColor: 'transparent',
    zIndex: 10,
  },
  downloadButton: {
    bottom: 20,
    left: 20,
    backgroundColor: '#4caf50',
  },
  downloadingButton: {
    backgroundColor: '#ff9800',
  },
  downloadedButton: {
    backgroundColor: '#666666',
  },
  updateButton: {
    backgroundColor: '#2196f3',
  },
  deleteButton: {
    backgroundColor: '#f44336',
  },
  audioButton: {
    bottom: 20,
    right: 20,
    backgroundColor: '#9c27b0',
  },
  cornerButtonText: {
    color: '#ffffff',
    fontSize: 14,
    fontWeight: 'bold',
  },
  backButton: {
    position: 'absolute',
    top: 20,
    left: 20,
    backgroundColor: '#666666',
    paddingHorizontal: 20,
    paddingVertical: 12,
    borderRadius: 20,
    borderWidth: 2,
    borderColor: 'transparent',
    zIndex: 10,
  },
  backButtonText: {
    color: '#ffffff',
    fontSize: 14,
    fontWeight: 'bold',
  },
  remoteHintContainer: {
    position: 'absolute',
    top: 20,
    right: 20,
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    paddingHorizontal: 15,
    paddingVertical: 8,
    borderRadius: 10,
    zIndex: 5,
    width: (width - height - 80) / 2,
  },
  remoteHintText: {
    color: '#ffffff',
    fontSize: 12,
    textAlign: 'center',
    fontWeight: '500',
  },
});

export default CardView; 